package com.hhq.sso.system.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.hhq.sso.common.exception.BusinessException;
import com.hhq.sso.common.util.WebContext;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.CacheUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import com.hhq.sso.system.entity.Dept;
import com.hhq.sso.system.mapper.DeptMapper;
import com.hhq.sso.system.service.IDeptService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Override
    public IPage<Dept> selectDeptPage(IPage<Dept> page, Dept dept) {
        return page.setRecords(baseMapper.selectDeptPage(page, dept));
    }

    @Override
    public List<Dept> tree(String tenantId) {
        return ForestNodeMerger.merge(baseMapper.tree(tenantId));
    }

    @Override
    public String getDeptIds(String tenantId, String deptNames) {
        List<Dept> deptList = baseMapper.selectList(Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId)
            .in(Dept::getDeptName, Func.toStrList(deptNames)));
        if (deptList != null && deptList.size() > 0) {
            return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
        }
        return null;
    }

    @Override
    public List<String> getDeptNames(String deptIds) {
        return baseMapper.getDeptNames(Func.toLongArray(deptIds));
    }

    @Override
    public boolean submit(Dept dept) {
        CacheUtil.clear(CacheUtil.SYS_CACHE);
        if (Func.isEmpty(dept.getParentId())) {
            dept.setTenantId(WebContext.getTenantId());
            dept.setParentId(BladeConstant.TOP_PARENT_ID);
            dept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
        }
        if (dept.getParentId() > 0) {
            Dept parent = getById(dept.getParentId());
            if (Func.toLong(dept.getParentId()) == Func.toLong(dept.getId())) {
                throw new BusinessException("父节点不可选择自身!");
            }
            dept.setTenantId(parent.getTenantId());
            String ancestors = parent.getAncestors() + StringPool.COMMA + dept.getParentId();
            dept.setAncestors(ancestors);
        }
        dept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
        return saveOrUpdate(dept);
    }

}
